<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-alert title="添加商品信息" type="info" :closable="false" show-icon center>
      </el-alert>

      <!-- 添加商品步骤条 -->
      <el-steps :active="activeIndex - 0" :space="200" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 步骤标签页 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
        <el-tabs v-model="activeIndex" :tab-position="'left'" :before-leave="beforeTabLeave" @tab-click="tabClicked">
          <el-tab-pane label="基本信息" name="0">
						<el-form-item label="商品分类" prop="goods_cat">
						  <el-cascader :options="goodsCateList" :props="cateProps" v-model="addForm.goods_cate" @change="goodsCateChanged" clearable>
						  </el-cascader>
						</el-form-item>
            <el-form-item label="商品名称" prop="goods_name">
                <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
                <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
						<el-form-item label="商品销售价格" prop="goods_msg_price">
						    <el-input v-model="addForm.goods_msg_price" type="number"></el-input>
						</el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
                <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
                <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
						<el-button type="primary" size="mini" @click="addDialogVisible = true">添加参数</el-button>
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item._id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="item1" v-for="(item1, index) in item.attr_vals" :key="index" border size="small"></el-checkbox>
								<el-input class="input-new-tag" v-if="item.inputVisible" v-model="item.inputValue" ref="saveTagInput" size="small"
								@keyup.enter.native="handleInputConfirm(item)" @blur="handleInputConfirm(item)">
								</el-input>
								<el-button v-else class="button-new-tag" size="small" @click="showInput(item)">+ New Tag</el-button>
              </el-checkbox-group>
							
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
						<el-button type="primary" size="mini" @click="addDialogVisible = true">添加属性</el-button>
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item._id">
                <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload 
						:action="api_upload" 
						:on-preview="handlePreview" 
						:on-remove="handleRemove"
						:multiple="true"
						list-type="picture"
						:on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_content"></quill-editor>
            <!-- 添加商品按钮 -->
            <el-button type="primary" class="btnAdd" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
		
		<!-- 添加动态参数或添加静态属性对话框 -->
		<el-dialog :title="'添加' + titleText" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
		  <!-- 添加参数的对话框 -->
		  <el-form :model="addAttrForm" :rules="addAttrFormRules" ref="addAttrFormRef" label-width="100px">
		    <el-form-item :label="titleText + '：'" prop="attr_name">
		      <el-input v-model="addAttrForm.attr_name"></el-input>
		    </el-form-item>
		  </el-form>
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="addDialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="addParams">确 定</el-button>
		  </span>
		</el-dialog>

    <!-- 图片预览 -->
    <el-dialog title="提示" :visible.sync="previewVisible" width="30%">
      <img :src="previewPath" class="preivewImg" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
import Vue from 'vue'
export default {
  data () {
    return {
			api_url: this.$api_url,
			api_upload: this.$api_upload,
      activeIndex: '0',
			currentCateId: 0,
      // 添加商品的表单数对象
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_msg_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品所属的分类
        goods_cate: '',
        // 图片的数组
        goods_imgs: [],
        // 商品的详情描述
        goods_content: '',
				// 动态参数
				goods_dy_attr: [],
				// 静态属性
				goods_static_attr: [],
				// 商品所属店铺
				goods_store: ''
      },
      // 添加商品表单的验证规则对象
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
				goods_msg_price: [
				  { required: true, message: '请输入商品销售价格', trigger: 'blur' }
				],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cate: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
			// 控制添加对话框的显示与隐藏
			addDialogVisible: false,
			// 添加参数的表单数据对象
			addAttrForm: {
				attr_name:''
			},
			// 添加参数的表单验证对象
			addAttrFormRules: {
			  attr_name: [
			    { required: true, message: '请输入参数名称', trigger: 'blur' }
			  ]
			},
      // 商品分类列表
      goodsCateList: [],
      cateProps: {
        value: '_id',
        label: 'title',
        children: 'children',
        expandTrigger: true,
        checkStrictly: true
      },
      // 级联选择器绑定Id数组
      selectedKeys: [],
      // 动态参数列表数据
      manyTableData: [],
      // 静态属性列表数据
      onlyTableData: [],
      // 上传图片的URL地址
      uploadURL: 'http://localhost:3000/upload',
      // 图片上传组件的headers请求头对象
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 预览图片的地址
      previewPath: '',
      // 图片预览的显示与隐藏
      previewVisible: false,
			// 商品所属id
			goods_store:''
    }
  },
  created () {
		this.addForm.goods_store = JSON.parse(window.sessionStorage.getItem('storeinfo'))._id;
		console.log(this.addForm.goods_store);
    // 获取所有的商品分类列表
    this.getCateList()
  },
  methods: {
    // 获取所有的商品分类数据
    async getCateList () {
			const { data: res } = await this.$http.get('categories')
			if (res.code !== 200) return this.$message.error(res.msg)
			this.$message.success(res.msg)
			this.goodsCateList = res.data;
			console.log(this.goodsCateList)

    },
    goodsCateChanged () {
      console.log(this.addForm.goods_cate)
			// 每次改变分类重置参数和属性数据请求
			this.currentCateId = 0;
      if (this.addForm.goods_cate.length !== 3) {
        this.addForm.goods_cate = [];
      }
    },
    // 标签页切换事件
    beforeTabLeave (activeName, oldActiveName) {
      // console.log('即将离开的标签页名字是：' + oldActiveName)
      // console.log('即将进入的标签页名字是：' + activeName)
      // return false
      if (oldActiveName === '0' && this.addForm.goods_cate.length !== 3) {
        this.$message.error('请先选择商品分类！')
        return false
      }
    },
    // 商品参数点击事件
    async tabClicked () {
			this.currentCateId++;
      console.log(this.currentCateId)
			
      if (this.activeIndex === '1') {
				if (this.currentCateId > 1) return;
        const { data: res } = await this.$http.get(`categories/params/1/${this.cateId}`)
				console.log('attr',res);
				if (res.code !== 200) return this.$message.error(res.msg)
				this.$message.success(res.msg)
				res.data.forEach(item => {
				  // 控制文本款的显示与隐藏
				  item.inputVisible = false
				  // 文本框中输入的值
				  item.inputValue = ''
				})
        this.manyTableData = res.data;
				
      } else if (this.activeIndex === '2') {
				if (this.currentCateId > 2) return;
        const { data: res } = await this.$http.get(`categories/params/2/${this.cateId}`)
        if (res.code !== 200) return this.$message.error(res.msg)
				this.$message.success(res.msg)
        console.log('val',res.data)
        this.onlyTableData = res.data;
				this.onlyTableData.forEach(item => {
					item.attr_vals = item.attr_vals.join(' ');
				})
      }
    },
    // 处理图片预览效果
    handlePreview (file) {
      // console.log(file)
      this.previewPath = file.response.data.url
      // console.log(previewPath)
      this.previewVisible = true
    },
    // 处理移除图片的操作
    handleRemove (file) {
      console.log(file)
			// 1.获取将要删除的图片的临时路径
			const filePath = file.response[0].file;
			// 2.从pics数组中,找到这图片对应的索引值
			const index = this.addForm.goods_imgs.findIndex(x => x === filePath);
			// 3.调用数组的splice方法,把图片信息对象从pics数组中移除
			this.addForm.goods_imgs.splice(index, 1)
			console.log('img',this.addForm.goods_imgs)
    },
    // 监听图片上传成功的事件
    handleSuccess (res) {
      console.log(res)
      // 1.拼接得到一个图片信息对象
      // 2.将图片信息对象 push 到pics数组中
      this.addForm.goods_imgs.push(res[0].file)
      console.log(this.addForm.goods_imgs)
    },
    // 添加商品
    add () {
			// console.log('form',this.addForm)
			// console.log(this.manyTableData,this.onlyTableData)
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项！')
        }
        // 执行添加的业务逻辑
        const form = _.cloneDeep(this.addForm)
        form.goods_cate = form.goods_cate[form.goods_cate.length-1];
        // 处理动态参数
        this.manyTableData.forEach(item => {
          form.goods_dy_attr.push({
						attr_name: item.attr_name, 
						attr_vals: item.attr_vals
					})
        })
        // 处理静态属性
        this.onlyTableData.forEach(item => {
					form.goods_static_attr.push({
						attr_name: item.attr_name, 
						attr_vals: item.attr_vals
					})
        })

        console.log(form)
				// return;
        const { data: res } = await this.$http.post('goods', form)
        if (res.code !== 200) return this.$message.error(res.msg)
				console.log(res);
        this.$message.success(res.msg)
        this.$router.push('/goods')
      })
    },
		// 文本款失去焦点,或按下了ENTER都会触发
		async handleInputConfirm (item) {
		  // console.log('ok')
		  if (item.inputValue.trim().length === 0) {
		    item.inputValue = ''
		    item.inputVisible = false
		    return
		  }
		  // 如果没有return,则证明输入的内容,需要做后续处理
		  item.attr_vals.push(item.inputValue.trim())
		  item.inputValue = ''
		  item.inputVisible = false
			console.log(item.attr_vals);
		  // 需要发起请求保存这次操作
		  // this.saveAttrVals(item)
		},
		// 点击按钮,展示文本输入框
		showInput (item) {
		  item.inputVisible = true 
		  // 让文本框自动获得焦点
		  // $nextTick 方法的作用,就是当页面上元素被重新渲染之后,才会指定回调函数中的代码
		  this.$nextTick( () => {
		    this.$refs['saveTagInput'][0].$refs.input.focus()
		  })
		},
		// 删除对应的参数可选项
		handleClose (index, row) {
		  row.attr_vals.splice(index, 1)
		  this.saveAttrVals(row)
		},
		// 监听添加对话框的关闭事件
		addDialogClose () {
		  this.$refs.addAttrFormRef.resetFields()
		},
		// 点击按钮,添加参数
		addParams () {
			console.log(this.activeIndex,this.addAttrForm)
			if (this.activeIndex == 1) {
				this.manyTableData.push({
					attr_name: this.addAttrForm.attr_name.trim(),
					attr_vals: [],
					inputValue: '',
					inputVisible: false,
					add_time: Date.now
				})
				console.log(this.manyTableData)
			} else if (this.activeIndex == 2) {
				this.onlyTableData.push({
					attr_name: this.addAttrForm.attr_name.trim(),
					attr_vals: '',
					inputValue: '',
					inputVisible: false,
					add_time: Date.now
				})
				console.log(this.onlyTableData)
			}
			this.addDialogVisible = false
		},
  },
  computed: {
    cateId () {
      if (this.addForm.goods_cate.length === 3) {
        return this.addForm.goods_cate[1]
      }
      return null
    },
		// 动态计算标题的文本
		titleText () {
		  if (this.activeIndex === '1') {
		    return '动态参数'
		  } 
			
			return '静态属性'
		}
  }
}
</script>

<style lang="less" scoped>
  .el-checkbox {
    margin: 0 10px 0 0 !important;
  }

  .preivewImg {
    width: 100%;
  }

  .btnAdd {
    margin-top: 15px;
  }
	.el-form-item {
		margin-bottom: 0;
	}
	.input-new-tag {
	  width: 120px;
	}
</style>
